<!--
    group: 发票管理
    name: 申请开票
    item: 开票类目--子子组件
-->
<template>
  <a-row type="flex" justify="space-between" class="box">
    <a-col :span='6' class="rightLine padding">
      <a-select
        show-search
        allowClear
        placeholder="请选择一级类目"
        optionLabelProp="value"
        v-model="item.name"
        :filter-option="filterOption"
        @change="handleChange"
      >
        <a-select-option v-for="item in optionData" :value="item.keyValue" :item="item">
          {{ item.keyValue }}
        </a-select-option>
      </a-select>
      <a-auto-complete
        allowClear
        class="mTop"
        :disabled="item.name ? false : true"
        style="width: 100%"
        placeholder="请输入二级类目"
        v-model="item.value"
        optionLabelProp="value"
        :filter-option="filterOption"
        @focus="onFocus"
        @select="onSelect"
      >
        <template slot="dataSource">
          <a-select-option v-for="item in secondList" :value="item.keyValue" :item="item">
            <span :style="{color:item.ultraLimit == 1 ? 'red' : ''}">{{ item.keyValue }}</span>
          </a-select-option>
        </template>
      </a-auto-complete>
      <span class="red" v-if="item.ultraLimit != 0">请按照实际经营活动选择开票类目，我司将按您提交的开票类目进行赋码开具发票，如税收编码与实际服务场景不匹配，可能会触发发票开具风险预警，请确保一致。</span>
    </a-col>
    <a-col :span='2' class="align rightLine tone padding"> <!--规格-->
      <a-input v-model="item.spec" type="text" :maxLength="40" class="w100" />
    </a-col>
    <a-col :span='2' class="align rightLine tone padding"> <!--单位-->
      <a-input v-model="item.unit" type="text" placeholder="选填" :maxLength="10" class="w100" />
    </a-col>
    <a-col :span='2' class="align rightLine tone padding"> <!--数量-->
      <a-input-number v-model="item.num" placeholder="选填" :min="1" :precision="0" class="w100" />
    </a-col>
    <a-col :span='2' class="align rightLine padding"> <!--单价-->
      <div>{{ item.unitPrice }}</div>
    </a-col>
    <a-col :span='3' class="align rightLine tone padding"> <!--金额-->
      <a-input-number v-model="item.taxMoney" :disabled="moneyDisabled" placeholder="不含税金额" @change="funChange" :formatter="limitNumber" :parser="limitNumber" class="w100" />
    </a-col>
    <a-col :span='2' class="align rightLine padding"> <!--税率-->
      <!-- 专票税率  vatIndex -->
      <div v-if="newTaxType==1">
        <template v-if="index==0">
          <a-select v-model="vatNewIndex" @change="selectRate">
            <a-select-option
              v-for="(jery,ind) in vatRates"
              :value="jery.vatIndex"
              :val="jery.value"
              :key="ind"
            >{{ jery.value ? jery.value : 0 }}%</a-select-option>
          </a-select>
        </template>
        <span v-else>{{ newVatRate }}%</span>
      </div>
      <!-- 普票税率  -->
      <span v-if="taxType==2" style="line-height: 30px;">1%</span>
    </a-col>
    <a-col :span='2' class="align rightLine padding"> <!--税额-->
      <span style="line-height: 30px;">{{ item.taxLimit }}</span>
    </a-col>
    <a-col :span='3' class="align tone padding"> <!--价税合计-->
      <a-input-number v-model="item.money" :disabled="moneyDisabled" placeholder="含税金额" :formatter="limitNumber" :parser="limitNumber" class="w100" />
    </a-col>

    <!--优惠政策弹层-->
    <div class="policy" v-if="visible">
      <div class="flex" style="justify-content: space-between;">
        <h4>
          您在2023年1月1日以后取得的适用3%征收率的应税销售收入，可
          减按1%征收率征收增值税。若您有特殊情况，需要开具其他发票，请
          按提示选择相应原因:
        </h4>
        <a-icon class="close" type="close" @click="hide" />
      </div>
      <a-radio-group v-model="policy.explain" @change="onPoliciesChange">
        <a-radio :value="1">前期已开具发票，发生销售折让、中止或者退回等情形<br/>需要开具红字发票，或者开票有误需要重新开具。</a-radio>
        <a-radio :value="2">因为实际经营业务需要，放弃享受减按1%征收率征收<br/>增值税政策</a-radio>
      </a-radio-group>
    </div>
  </a-row>
</template>

<script>
import { mapState,mapGetters } from 'vuex'
import { conversionElement,conversionBranch,limitDigits,limitInput,percentageConverse } from '@/utils/util'
import {cloneObject} from "@/utils/util";
import { getIndustryInfoChild } from '@/api/invoiceAdminister'
export default {
  name: "invoicingDropDownItem",
  data(){
    return{
      treeData: [],  //开票类目
      invoiceTypeName: '',
      replaceFields: {
        title: 'keyValue',
        key: 'id',
        children: 'node',
        value: 'keyCode',
      },

      // vatRate: null,  //专票税率
      newVatRate: null,  //专票税率
      vatNewIndex: null,
      newTaxType: null,
      visible: false,

      //优惠政策原因↓
      policy:{
        explain: null,  //原因
        vatReason: null,  //释义
      },
      policiesReasons:{
        1: '前期已开具发票，发生销售折让、中止或者退回等情形需要开具红字发票，或者开票有误需要重新开具。',
        2: '因为实际经营业务需要，放弃享受减按1%征收率征收增值税政策'
      },

      secondList: [], //调取二级接口类目

      moneyDisabled: false,
    }
  },
  props: ['item','index','optionData','changeEvent','rangeEvent','vatRates'],
  computed: {
    ...mapState({
      vatIndex: state => state.invoice.vatIndex,  //专票增值税id
      vatRate: state => state.invoice.vatRate,  //专票增值税税率
      taxType: state => state.invoice.taxType,  //发票类型
    }),
  },
  created() {
    this.vatNewIndex = this.vatIndex;
    this.newVatRate = this.vatRate;
    this.newTaxType = this.taxType;
    //从详情 变更申请 发起
    if (this.$route.query.varyType && this.$route.query.varyType == 1){
      this.moneyDisabled = true;
    }
  },
  watch:{
    'taxType':{
      immediate: true,  //初始值执行函数
      deep: false,  //深度监听
      handler (newVal,oldVal) {
        // console.log('taxType==>  ' + newVal)
        this.newTaxType = newVal;
        if (newVal == 2) {
          this.newVatRate = 1;
        } else {
          this.newVatRate = this.vatRate;
        }
      }
    },
    'vatRate':{
      immediate: true,  //初始值执行函数
      deep: false,  //深度监听
      handler (newVal,oldVal) {
        this.newVatRate = newVal;
        this.vatNewIndex = this.vatIndex;
        // console.log('newVatRate==>  ' + this.newVatRate)

        //税率 + 含税金额
        if (newVal && this.item.money) {
          //金额（不含税）=开票金额（含税）/（增值税税率（专可变 普1）+1）
          this.item.taxMoney = conversionElement(conversionBranch(this.item.money) / (percentageConverse(this.newVatRate) + 1)).toFixed(2); //不含税金额
          //税额 = 不含税金额÷（1+增值税税率）x 增值税税率
          this.item.taxLimit = conversionElement(conversionBranch(this.item.money) / (percentageConverse(this.newVatRate) + 1) * percentageConverse(this.newVatRate)).toFixed(2);  //税额

          //数量 + 不含税金额
          if (this.item.num && this.item.taxMoney){
            //单价 = 不含税金额/数量
            this.item.unitPrice = conversionElement(conversionBranch(this.item.taxMoney) / this.item.num);
          }
        }else{
          //税率 + 不含税金额
          if (newVal && this.item.taxMoney) {
            //含税金额 = 不含税金额 * 增值税税率 + 不含税金额
            this.item.money = conversionElement(conversionBranch(this.item.taxMoney) * (percentageConverse(this.newVatRate) + 1)).toFixed(2);
            //税额 = 不含税金额 x 增值税税率
            this.item.taxLimit = conversionElement(conversionBranch(this.item.taxMoney) * percentageConverse(this.newVatRate)).toFixed(2);

            //数量
            if (this.item.num){
              //单价 = 不含税金额/数量
              this.item.unitPrice = conversionElement(conversionBranch(this.item.taxMoney) / this.item.num);
            }
          }
        }

        this.$forceUpdate();  //数据更新
      }
    },
    // 监听data多个数据变化
    item:{
      handler:function(val) {
        // console.log('开票金额 ==》 ',val)
        if (val.money && this.$route.query.detailsId){
          //不含税金额
          this.item.taxMoney = conversionElement(conversionBranch(val.money) / (percentageConverse(this.vatRate) + 1)).toFixed(2);
          this.item.taxLimit = conversionElement(conversionBranch(val.money) / (percentageConverse(this.vatRate) + 1) * percentageConverse(this.vatRate)).toFixed(2);
        }
      },
      immediate: true,
      deep: false,  //深度监听
    },
    'item.num': function (val) {
      //当数量 + 税率有值时
      if (val && this.newVatRate){
        //当不含税金额有值 + 含税金额无值
        if (this.item.taxMoney && !this.item.money){
          //单价 = 不含税金额/数量
          this.item.unitPrice = conversionElement(conversionBranch(this.item.taxMoney) / val);

          //含税金额 = 不含税金额 * 增值税税率 + 不含税金额
          this.item.money = conversionElement(conversionBranch(this.item.taxMoney) * (percentageConverse(this.newVatRate) + 1)).toFixed(2);
          //税额 = 不含税金额 x 增值税税率
          this.item.taxLimit = conversionElement(conversionBranch(this.item.taxMoney) * percentageConverse(this.newVatRate)).toFixed(2);
        }
        //当不含税金额无值 + 含税金额有值
        else if (!this.item.taxMoney && this.item.money){
          //不含税金额 = 含税金额 / （增值税税率+1）
          this.item.taxMoney = conversionElement(conversionBranch(this.item.money) / (percentageConverse(this.newVatRate) + 1)).toFixed(2);
          //税额 = 不含税金额 ÷（1+增值税税率） x 增值税税率
          this.item.taxLimit = conversionElement(conversionBranch(this.item.money) / (percentageConverse(this.newVatRate) + 1) * percentageConverse(this.newVatRate)).toFixed(2);  //税额

          //单价 = 不含税金额/数量
          this.item.unitPrice = conversionElement(conversionBranch(this.item.taxMoney) / val);
        }
        //当不含税金额有值 + 含税金额有值
        else if (this.item.taxMoney && this.item.money){
          //单价 = 不含税金额/数量
          this.item.unitPrice = conversionElement(conversionBranch(this.item.taxMoney) / val);
        }
      }
      //当数量, 税率无值时
      else if (val && !this.newVatRate){
        //当不含税金额有值 + 含税金额无值
        if (this.item.taxMoney && !this.item.money){
          //单价 = 不含税金额/数量
          this.item.unitPrice = conversionElement(conversionBranch(this.item.taxMoney) / val);

          this.item.money = null;  //含税金额
        }
        //当不含税金额无值 + 含税金额有值
        else if (!this.item.taxMoney && this.item.money){
          this.item.taxMoney = null;  //不含税金额
        }
        this.item.taxLimit = null;   //税额
      }
      //当数量无值时
      else if (!val){
        this.item.unitPrice = null;   //单价
        this.item.num = null;   //数量
      }
    },
    'item.money': function (val){
      //当含税金额 + 税率有值时
      if (val && this.newVatRate){
        //不含税金额= 含税金额 / （增值税税率+1）
        this.item.taxMoney = conversionElement(conversionBranch(val) / (percentageConverse(this.newVatRate) + 1)).toFixed(2);
        //税额 = 不含税金额 ÷（1+增值税税率） x 增值税税率
        this.item.taxLimit = conversionElement(conversionBranch(val) / (percentageConverse(this.newVatRate) + 1) * percentageConverse(this.newVatRate)).toFixed(2);  //税额
        //当数量有值时
        if (this.item.num){
          //单价 = 不含税金额/数量
          this.item.unitPrice = conversionElement(conversionBranch(this.item.taxMoney) / this.item.num);
        }
      }
      //当含税金额, 税率无值时
      else if (val && !this.newVatRate){
        this.item.taxMoney = null;  //不含税金额
        this.item.taxLimit = null;   //税额
      }
    }
  },
  methods:{
    //不含税金额---值变化
    funChange(val){
      //当不含税金额 + 税率有值时
      if (val && this.newVatRate){
        //当数量有值时
        if (this.item.num){
          //单价 = 不含税金额/数量
          this.item.unitPrice = conversionElement(conversionBranch(val) / this.item.num);
        }

        //含税金额 = 不含税金额 * 增值税税率 + 不含税金额
        this.item.money = conversionElement(conversionBranch(val) * (percentageConverse(this.newVatRate) + 1)).toFixed(2);
        //税额 = 不含税金额 x 增值税税率
        this.item.taxLimit = conversionElement(conversionBranch(val) * percentageConverse(this.newVatRate)).toFixed(2);
      }
      //当不含税金额, 税率无值时
      else if (val && !this.newVatRate){
        this.item.money = null;  //含税金额
        this.item.taxLimit = null;  //税额
        //当数量有值时
        if (this.item.num){
          //单价 = 不含税金额/数量
          this.item.unitPrice = conversionElement(conversionBranch(val) / this.item.num);
        }
      }else {
        this.item.money = null;  //含税金额
        this.item.taxLimit = null;  //税额
        this.item.unitPrice = null;  //单价
      }
    },
    handleChange(value,option) {
      // console.log(`selected ${value}`);
      if (value){
        this.item.invoiceTypeCode = option.data.attrs.item.keyCode;
        //调取二级接口
        this.getMethodList(this.item.invoiceTypeCode);
      }else{
        this.item.name = null;
        this.item.value = null;
        this.item.invoiceTypeCode = null;
      }
    },
    filterOption(input, option) {
      // option.componentOptions.children[0].text.toLowerCase()为内容值
      // option.data.attrs.data_mobile 为绑定的属性值，可自行定义
      return (
        // option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        option.data.attrs.item.keyValue.indexOf(input.toLowerCase()) >= 0
      )
    },
    onFocus(){
      //调取二级接口
      this.getMethodList(this.item.invoiceTypeCode);
    },
    onSelect(value,option) {
      if (value){
        this.item.ultraLimit = option.data.attrs.item.ultraLimit;
      }else{
        this.item.ultraLimit = 1;
      }
      // console.log('onSelect', value);
    },
    //获取二级开票列表数据
    getMethodList(invoiceTypeCode){
      let params = {};
      params.entId = this.$route.query.bizId;
      params.parentGroupCode = invoiceTypeCode;
      getIndustryInfoChild(params).then(res => {
        if (res.success) {
          let data = res.result || [];
          this.secondList = data;
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //  ---------------------------- 校验规则 ↓ -------------------------------
    //正则替换小数点
    limitNumber(value){
      return limitDigits(value);
    },
    //  ---------------------------- 增值税税率计算 ↓ -------------------------------
    //专票税率选择
    selectRate(index, option){
      let val = option.data.attrs.val;
      // this.newVatRate = val;
      //存储vuex
      let str = {};
      str.vatRate = val;
      str.vatIndex = index;
      this.$store.dispatch('setInvoiceVatIndex', str);
      if (val == 3){
        this.visible = true;
      }
    },
    hide(){
      if (this.policy.explain){
        this.visible = false;
      }else{
        this.visible = true;
        this.$message.warning('请选择优惠政策原因');
      }
    },
    //选择优惠政策原因
    onPoliciesChange(e) {
      // console.log(e.target.value)
      this.policy.explain = e.target.value;
      this.policy.vatReason = this.policiesReasons[e.target.value];

      this.$store.dispatch('setInvoiceExplain', this.policy.vatReason);  //存储vuex
    },
    //获取对应id的value值  增值税
    obtainCorrespondingValue(id,list){
      let hh = list.filter(function (item, index, list) {//第一个参数为当前项,第二个参数为索引,第三个为原值
        if (item.vatIndex == id) {
          return item
        }
      })

      //获取当前value的值
      if (hh && hh.length > 0){
        return hh[0].value;
      }
    },
    //  ---------------------------- 开票操作 （作废） ↓ -------------------------------
    //开票内容选择
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        setTimeout(() => {
          this.treeData = [...this.treeData]
          resolve()
        }, 1000)
      })
    },
  }
}
</script>

<style lang="less">
//disabled色值更改
//li.ant-select-tree-treenode-disabled > span:not(.ant-select-tree-switcher),
//li.ant-select-tree-treenode-disabled > .ant-select-tree-node-content-wrapper,
li.ant-select-tree-treenode-disabled > .ant-select-tree-node-content-wrapper-open span {
  color: rgba(0, 0, 0, 0.65);
}
li.ant-select-tree-treenode-disabled > .ant-select-tree-node-content-wrapper-close span {
  color: rgba(0, 0, 0, 0.65);
}

li.ant-select-tree-treenode-disabled > .ant-select-tree-node-content-wrapper-normal span {
  color: rgba(0, 0, 0, 0.25);
}
</style>
<style lang="less" scoped>
//公共
.tone{color: #9D6854;}
.padding{padding: 5px;}
.mTop{margin-top: 10px;}
.topLine{border-top: 3px solid #9D6854;}
.rightLine{border-right: 3px solid #9D6854;}
.textLine{text-decoration: underline;cursor: pointer;}
.flex{display: flex;}
.align{text-align: center;}
.w100{width: 100%;}
.red{white-space: normal;}



.invoice_items{
  //display: flex;
//flex-wrap: wrap;
//  align-items: center;
  margin-bottom: 10px;
  .ant-input{
  //min-width: 200px;
    margin-right: 10px;
  }

  .InputBox{
    display: flex;
    align-items: center;
    margin-top: 10px;
  }

  /deep/.ant-select-selection--single{
    //width: 150px;
    margin-right: 10px;
  }
  /deep/.ant-select .ant-select-enabledr{
    width: auto!important;
  }


///deep/.ant-input-number{
  //  width: 200px;
  //}
///deep/.ant-input-number-input-wrap .ant-input-number-input{
//  width: 180px;
//}

  .ant-input-number{
    width: 110px;
    margin-right: 10px;
    /deep/.ant-input-number-handler-wrap{
      display: none;//去掉右边部分
    }
  }

  .tips{
    margin-left: 20px;
    font-size: 14px;
    white-space: nowrap;
    color: @color-lightGary;
  }
}


//优惠政策弹层
.box{
  position: relative;
}
.policy{
  width: 400px;
  position: absolute;
  top: 47%;
  right: 17%;
  z-index: 10;
  background: #FFFFFF;
  box-shadow: 3px 2px 10px #d9d9d9;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  padding: 10px 10px 30px 10px;
  h4{
    margin-right: 15px;
    margin-bottom: 20px;
  }
  .close{
    position: absolute;
    top: 10px;
    right: 10px;
  }
}

.gary{
  color: #9e9e9e;
  font-size: 16px;
}

/deep/.ant-input-affix-wrapper .ant-input:not(:first-child) {
  //padding-left: 50%;
  padding-left: 105px;
}
</style>

